// 自定义模块，这里只需要开放soulTable即可
layui.config({
    base: '../../../iemes/lib/soulTable/', // 第三方模块所在目录
    version: 'v1.5.21' // 插件版本号
}).extend({
    soulTable: 'soulTable',
    tableChild: 'tableChild',
    tableMerge: 'tableMerge',
    tableFilter: 'tableFilter',
    excel: 'excel',
});
var atObjHtml = window.parent.navHref;

var tree = {
    options: null,
    leftTreeId: 'leftTree',
    atObj: {
        htmlTreeName: null
    } //当前点击或选择的树形值
},
    extObj = {}; //修改对象;

layui.extend({
    dtree: '../../../iemes/lib/layui_ext/dtree/dtree' // {/}的意思即代表采用自有路径，即不跟随 base 路径
}).use(['element', 'soulTable', 'dtree', 'layer', 'jquery', 'form', 'layedit', 'laydate', 'table', 'laytpl'], function () {
    $_$ = layui.jquery,
        element = layui.element,
        soulTable = layui.soulTable,
        form = layui.form,
        layedit = layui.layedit,
        laydate = layui.laydate,
        table = layui.table,
        laytpl = layui.laytpl,
        dtree = layui.dtree,
        layer = layui.layer;

    layer.config({
        skin: 'layui-layer-molv'
    })

    //加载弹框
    // globalParentLoadingFun();

    //定时器 查找是否找到按钮后结束加载弹框
    var ma = setInterval(function () {
        console.log('TabFrame', atObjHtml)
        if (atObjHtml != null) {
            window.parent.setProgressFun(null, 25)
            tabElemId = atObjHtml.tabElemid;
            $_$('.layui-hide').attr('id', atObjHtml.tabElemid).attr('lay-filter', atObjHtml.tabElemid)
            //表头参数请求
            tabInitMain();
            this.clearInterval(ma); //清除定时器
        }
    }, 400);
    //页面开始方法
    function tabInitMain() {
        switch (tabElemId) {
            case 'Desc':
                initCols(oveUrl + "/layuiTabCols/seleTab")
                break;
            case 'useTab':
                AJAX(oveUrl + atObjHtml.tabRight, {
                    elem: "#" + tabElemId
                }, 'GET', null, null,
                    (r) => {
                        console.log(r)
                    },
                    function (r) {

                    });
                break;
            default:
                AJAX(oveUrl + "/layuiTabCols/seleTab", {
                    // AJAX(oveUrl + atObjHtml.tabRight, {
                    elem: "#" + tabElemId
                }, 'GET', null, null,
                    (r) => {
                        console.log(r)
                        switch (r.code) {
                            case 200:
                                layui.each(r.data, (i, l) => {
                                    delete l.creationDate;
                                    delete l.updateDate;

                                    if (l.filter != undefined) {
                                        try {
                                            l.filter = JSON.parse(l.filter);
                                        } catch (error) {
                                            console.log('转对象错误')
                                        }
                                        // l.filter = l.filter === 'true';
                                    }
                                })
                                initCols(oveUrl + atObjHtml.tabRight, [r.data])
                                break;
                            default:
                                layer.msg(r.msg);
                                break;
                        }
                    },
                    function (r) {

                    });
                break;
        }
        window.parent.setProgressFun(null, 25)
    }


    //监听双击事件（双击事件为：rowDouble）
    table.on('rowDouble(' + atObjHtml.tabElemid + ')', function (obj) {
        console.log(obj);
        // setTabColor(data.color, data.colorName, false); //初始化颜色表格
    });

    //头工具栏事件
    table.on('toolbar(' + atObjHtml.tabElemid + ')', function (obj) {
        var tool = layer.load(2, {
            time: 30000,
            shade: 0.3
        });

        var checkStatus = table.checkStatus(obj.config.id);
        console.log(obj)
        console.log('选择对象', checkStatus)
        switch (obj.event) {
            case 'clearFilter':
                console.log(obj.event);
                soulTable.clearFilter(tabElemId);
                break;
            case 'batAddTree':

                break;
            case 'newDBBtu':
                crePopenObj = crePopenObjFun('创建', 1, $_$('#TC'), null, ['提交', '重置'],
                    function (index, layero) {
                        $_$('#TC [lay-ty="c"]').click();
                    },
                    function (index, layero) {
                        $_$('[lay-ty="lo"]').click();
                        return false
                    },
                    null, () => { },
                    function (layero, index) {
                        form.val('batTabEditForm', {
                            tabElem: tree.atObj.htmlTreeName.split('-')[1]
                        })
                    },
                    function () { //弹框销毁时执行
                        $_$('[lay-ty="lo"]').click();
                        tree.atObj == null
                        window.parent.left.isOPO = true;
                    }
                )


                break;
            case 'delMore':
                if (checkStatus.data.length != 0) {
                    delObjData(null, checkStatus.data);
                } else {
                    layer.msg('未选择');
                }
                break;
            case 'export':
                soulTable.export(tabElemId);
                break;
            case 'reload':
                table.reload(tabElemId, {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    },
                    where: {
                        elem: null,
                    }
                });
                break;
            default:
                break;
        }
        layer.close(tool);
    });

    //监听行工具事件
    table.on('tool(' + atObjHtml.tabElemid + ')', function (obj) {
        window.parent.left.isOPO = false;
        var tool = layer.load(2, {
            time: 30000,
            shade: 0.3
        });
        console.log(obj)
        var data = obj.data;
        console.log(data)
        if (obj.event === 'edit') { //编辑
            var f = form.val('batTabEditForm', obj.data)
            console.log('渲染后', f);
            extObj = {
                id: obj.data.tableId,
                data: JSON.parse(JSON.stringify(f))
            }
            crePopenObj = crePopenObjFun('修改', 1, $_$('#TC'), null, ['提交', '重置'],
                function (index, layero) {
                    $_$('#TC [lay-ty="ex"]').click();
                },
                function (index, layero) {
                    $_$('[lay-ty="lo"]').click();
                    return false
                },
                null, () => { },
                function (layero, index) {

                },
                function () { //弹框销毁时执行
                    extObj = null
                    $_$('[lay-ty="lo"]').click();
                    tree.atObj == null
                    window.parent.left.isOPO = true;
                }
            )
        } else if (obj.event === 'del') { //删除
            delObjData(obj, [data], tool);
        }
        layer.close(tool);
    });

    //弹框方法
    function crePopenObjFun(title, type, content, area, btn, btn_yes, btn_yes2, btn_yes3, cancelFun, successFun, endFun) {
        let end = endFun == null ? function () { } : endFun;
        let cancel = cancelFun;
        let success = successFun;
        let yes = btn_yes;
        let btn2 = btn_yes2;
        let btn3 = btn_yes3;
        return layer.open({
            title,
            type,
            skin: 'layui-layer-molv',
            area: area == null ? ['90%', '100%'] : area,
            content,
            btnAlign: 'c',
            scrollbar: false,
            btn,
            yes: function (index, layero) {
                yes(index, layer);
            },
            btn2: function (index, layero) {
                btn2(index, layer);
                return false
            },
            btn3: function (index, layero) {
                btn3(index, layer);
                return false
            },
            cancel: function (index, layero) {
                cancel(index, layero);
            },
            success: function (layero, index) {
                success(layero, index)
            },
            end: function () { //弹框销毁时执行
                end();
            }
        })
    }

    /*
     * 初始化表格 表头
     */
    function initCols(url, cols, data) {
        console.log('表头', cols)
        console.log('数据', data)
        cols = cols == null ? [
            [{
                type: 'checkbox',
                fixed: 'left'
            }, {
                field: 'tableId',
                title: 'ID',
                width: 80,
                sort: true,
                filter: true
            }, {
                field: 'inliOrder',
                hide: true,
                title: '顺序',
                width: 80,
                sort: true,
                filter: true
            }, {
                field: 'tabElem',
                title: 'tab表格ID',
                width: 110,
                sort: true,
                filter: true
            }, {
                field: 'field',
                title: '唯一标识',
                width: 110,
                sort: true,
                filter: true
            }, {
                field: 'title',
                title: '标题名称',
                width: 110,
                sort: true,
                filter: true
            }, {
                field: 'width',
                title: '设定列宽',
                width: 110,
                sort: true,
                filter: true
            }, {
                field: 'minWidth',
                title: '最小宽度',
                width: 110,
                sort: true,
                filter: true
            }, {
                field: 'type',
                title: '列类型',
                width: 100,
                sort: true,
                filter: true
            }, {
                field: 'LAY_CHECKED',
                title: '是否全选状态',
                width: 130,
                sort: true,
                filter: true
            }, {
                field: 'fixed',
                title: '固定列',
                width: 100,
                sort: true,
                filter: true
            }, {
                field: 'hide',
                title: '藏列',
                width: 80,
                sort: true,
                filter: true
            }, {
                field: 'totalRow',
                title: '自动合计',
                width: 130,
                sort: true,
                filter: true
            }, {
                field: 'totalRowText',
                title: '合计文本',
                width: 130,
                sort: true,
                filter: true
            }, {
                field: 'sort',
                title: '排序',
                width: 80,
                sort: true,
                filter: true
            }, {
                field: 'unresize',
                title: '拖拽列宽',
                width: 130,
                sort: true,
                filter: true
            }, {
                field: 'edit',
                title: '编辑类型',
                width: 130,
                sort: true,
                filter: true
            }, {
                field: 'event',
                title: '点击事件名',
                width: 150,
                sort: true,
                filter: true
            }, {
                field: 'style',
                title: '自定义单元格样式',
                width: 160,
                sort: true,
                filter: true
            }, {
                field: 'align',
                title: '单元格排列方式',
                width: 160,
                sort: true,
                filter: true
            }, {
                field: 'colspan',
                title: '单元格所占列数',
                width: 160,
                sort: true,
                filter: true
            }, {
                field: 'rowspan',
                title: '单元格所占行数',
                width: 160,
                sort: true,
                filter: true
            }, {
                field: 'templet',
                title: '自定义列模板',
                width: 160,
                sort: true,
                filter: true
            }, {
                field: 'toolbar',
                title: '绑定工具条模板',
                width: 160,
                sort: true,
                filter: true
            }, {
                field: 'creationDate',
                title: '创建时间',
                width: 200,
                sort: true,
                filter: true,
                filter: {
                    type: 'date[yyyy-MM-dd HH:mm:ss]'
                }
            }, {
                field: 'updateDate',
                title: '修改时间',
                width: 200,
                sort: true,
                filter: true,
                filter: {
                    type: 'date[yyyy-MM-dd HH:mm:ss]'
                }
            }, {
                fixed: 'right',
                title: '操作',
                toolbar: '#bar',
                width: 165
            }]
        ] : cols
        tab = table.render({
            id: tabElemId,
            elem: '#' + tabElemId,
            url,
            toolbar: '#toolbar', //开启头部工具栏，并为其绑定左侧模板
            headers: {
                "jwt": ajax_headers
            },
            defaultToolbar: ['filter', 'exports'],
            height: 'full-50',
            cellMinWidth: 80,
            page: true,
            response: {
                statusCode: 200 //规定成功的状态码，默认：0
            },
            cols,
            done: function (res, curr, count) {
                console.log('done方法触发', res);
                soulTable.render(this);
                window.parent.setProgressFun(null, 50)
            }
        });
        console.log('tab', tab)
        //关闭加载
        globalParentLoadingFunClose();
    }

    // 树形 点击节点触发回调，其中obj内包含丰富的数据，打开浏览器F12查看！
    dtree.on("node('leftTree')", function (obj) {
        console.log(dtree.getAllParentParam('leftTree', obj.param.nodeId));
        var Parent = dtree.getAllParentParam('leftTree', obj.param.nodeId);
        console.log(obj); // 点击当前节点传递的参数
        var data = obj.param;
        switch (treeExBat[0]) {
            case 'e':
                var ar = data.context.split('-')
                if (ar[1] != undefined) {
                    if (Parent.length != 0) {
                        $_$('#batTreeEdit [name="parentId"]').append('<option value="' + Parent[0].nodeId + '">' + Parent[0].context + '</option>');
                    } else {
                        $_$('#batTreeEdit [name="parentId"] option').remove();
                    }
                    form.val('batTreeEditForm', {
                        treeColsId: data.nodeId,
                        parentId: Parent.length != 0 ? Parent[0].nodeId : 0,
                        title: ar[0],
                        treeElem: ar[1]
                    }); //编辑赋值layui-this
                    form.render();
                    extObj = JSON.parse(JSON.stringify(form.val('batTreeEditForm')));
                }
                break;
        }
    });

    //监听 树形 提交
    form.on('submit(TreeCre)', function (data) {
        var treeParam = dtree.getNowParam('leftTree'); // 获取当前选中节点
        console.log(treeParam)
        var index = layer.load(2, {
            time: 30000,
            shade: 0.3
        });
        var a;
        if (a != null) {
            a.abort();
            layer.msg('稍后尝试')
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        }
        console.log(data)

        switch (data.elem.getAttribute('lay-ty')) {
            case 'c': //创建
                console.log('创建')
                console.log('par', tree.atObj)
                console.log('tree', tree.leftTree)
                console.log('treeo', tree.options)
                data.field.parentId = data.field.treeId
                data.field.treeColsName = data.field.title + '-' + data.field.treeElem
                console.log('提交数据', data.field);
                a = AJAX(oveUrl + "/layuiTabCols/creTree/", JSON.stringify(data.field), 'post', null, null, function (res) {
                    console.log(res)
                    if (res.code == 200) {
                        layer.closeAll();
                        if (res.data.parentId == undefined) {
                            res.data.parentId = 0
                        }
                        tree.options.data.push(res.data);
                        window.parent.left.initCodeTree(tree.options.data)
                    }
                });
                break;
            case 'ex': //修改
                console.log('extObj', extObj)

                if (data.field.treeId.length == 0) {
                    layer.msg('请选择需要修改的数据');
                    layer.close(index);
                    return false
                }

                if (JSON.stringify(extObj) == JSON.stringify(data.field)) {
                    layer.msg('未修改')
                    layer.close(index);
                } else {
                    // console.log('修改的数据', data.field)
                    // console.log('修改的数据', JSON.stringify(data.field))
                    data.field.treeColsName = data.field.title + '-' + data.field.treeElem
                    data.field.id = data.field.treeId

                    a = AJAX(oveUrl + "/layuiTabCols/updataTree/", JSON.stringify(data.field), 'PUT', null, null, function (res) {
                        // console.log(res)
                        if (res.code == 200) {
                            layer.closeAll();
                            layui.each(tree.options.data, (i, d) => {
                                if (parseInt(d.id) == parseInt(res.data.id)) {
                                    res.data.parentId == undefined ? res.data.parentId = 0 : res.data.parentId;
                                    tree.options.data[i] = res.data;
                                }
                            });
                            window.parent.left.initCodeTree(tree.options.data)
                        }
                    });
                }

                break;
            default:
                console.log('default')
                break;
        }
        return false;
    });

    //监听form表单提交  表格
    form.on('submit(tabCre)', function (data) {
        console.log(data);
        console.log(data.elem);
        console.log(data.field);

        var a;
        if (a != null) {
            a.abort();
            layer.msg('稍后尝试')
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        }

        switch (data.elem.getAttribute('lay-ty')) {
            case 'c': //创建
                a = AJAX(oveUrl + "/layuiTabCols/creTab/", JSON.stringify(data.field), 'post', true, null, function (res) {
                    console.log(res)
                    if (res.code == 200) {
                        var tabData = table.cache[tabElemId];
                        tabData.push(res.data);
                        console.log(tabData)
                        table.reload(tabElemId, {
                            data: tabData
                        });
                        layer.close(crePopenObj);
                    }
                });
                break;

            case 'ex': //修改
                if (JSON.stringify(data.field) == JSON.stringify(extObj.data)) {
                    layer.msg('未修改')
                } else {
                    data.field.tableId = extObj.id
                    a = AJAX(oveUrl + "/layuiTabCols/updataTab/", JSON.stringify(data.field), 'PUT', true, null, function (res) {
                        console.log(res)
                        if (res.code == 200) {
                            var tabData = table.cache[tabElemId];

                            tabData.push(res.data);
                            layui.each(tabData, (i, d) => {
                                if (parseInt(d.tableId) == parseInt(extObj.id)) {
                                    d = res.data
                                }
                            })
                            console.log(tabData)
                            table.reload(tabElemId, {
                                data: tabData
                            });
                            layer.close(crePopenObj);
                        }
                    });
                }
                break;

            default:
                break;
        }

        //关闭加载
        globalParentLoadingFunClose();
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });


    var treeExBat = []
    //树形弹出框
    var active = {
        addTree: function () {
            console.log('addTree')
            crePopenObj = crePopenObjFun('创建类型', 1, $_$('#batTreeEdit'), ['410px', '50%'], ['提交'],
                function (index, layero) {
                    $_$('#batTreeEdit [lay-ty="c"]').click();
                },
                function (index, layero) { },
                null, () => { },
                function (layero, index) {
                    tree.leftTree = dtree.render(tree.options);
                    $_$('[lay-ty="lo"]').click();
                },
                function () { //弹框销毁时执行
                    $_$('[lay-ty="lo"]').click();
                    window.parent.left.isOPO = true;
                })
        },
        redTree: function () {
            console.log('redTree')

            // $('#batTreeEdit [name="title"]')[1].setAttribute("custom", "title")//添加自定义属性 方便赋值
            // $('#batTreeEdit [name="treeElem"]').attr("custom", "treeElem")//添加自定义属性 方便赋值
            crePopenObj = crePopenObjFun('编辑类型', 1, $_$('#batTreeEdit'), ['410px', '50%'], ['提交'],
                function (index, layero) {
                    $_$('#batTreeEdit [lay-ty="ex"]').click();
                },
                function (index, layero) { },
                null, () => { },
                function (layero, index) {
                    treeExBat[0] = 'e';
                    tree.leftTree = dtree.render(tree.options);
                    $_$('[lay-ty="lo"]').click();
                },
                function () { //弹框销毁时执行
                    $_$('#batTreeEdit [name="parentId"] option').remove();
                    treeExBat[0] = null
                    extObj = null
                    $_$('[lay-ty="lo"]').click();
                    window.parent.left.isOPO = true;
                })

        },
        deleTree: function () {
            crePopenObj = crePopenObjFun('删除类型', 1, $_$('#batTreeEdit'), ['410px', '50%'], ['提交'],
                function (index, layero) {
                    var a;
                    if (a != null) {
                        a.abort();
                        layer.msg('稍后尝试')
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    }
                    var data = form.val('batTreeEditForm');
                    console.log('删除数据', data)
                    if (data.treeId != undefined) {
                        data.id = data.treeId;
                        data.treeColsName = data.htmlTreeName.split('-')[1];
                        layer.confirm('真的删除行么', function (index) {
                            a = AJAX(oveUrl + "/layuiTabCols/treeDele", JSON.stringify(data), 'DELETE', null, null, function (res) {
                                console.log(res)
                                if (res.code == 200) {
                                    layui.each(tree.options.data, (i, d) => {
                                        if (parseInt(d.id) == parseInt(data.treeId)) {
                                            tree.options.data.splice(i, 1);
                                        }
                                    })
                                    console.log('删除好的数据', tree.options.data)
                                    window.parent.left.initCodeTree(tree.options.data)
                                }
                                layer.close(crePopenObj);
                                layer.msg(res.msg, {
                                    time: 1000
                                });
                                window.parent.left.isOPO = true;
                            });
                        });

                    }
                },
                function (index, layero) { },
                null, () => { },
                function (layero, index) {
                    treeExBat[0] = 'e';
                    tree.leftTree = dtree.render(tree.options);
                    $_$('[lay-ty="lo"]').click();
                },
                function () { //弹框销毁时执行
                    treeExBat[0] = null
                    $_$('#batTreeEdit .tyle-name').css('display')
                    $_$('[lay-ty="lo"]').click();
                    window.parent.left.isOPO = true;
                })
            // console.log('deleTree')
            // $('#batTreeEdit').append($("label:contains('类型名称')").parent().css("display", "none"))
            // redTreePop('删除类型');
        }
    };

    $_$('#treeEdit .layui-btn').on('click', function () {
        var custom = $_$(this).attr('custom');
        console.log(this)
        layer.close(crePopenObj); //关闭弹出窗
        window.parent.left.isOPO = false;
        active[custom] ? active[custom].call(this) : '';
    });



    //添加input样式
    function addInputCssSty() {
        $('[lay-filter="batTreeEditForm"] [type="addColor"]').css("display", "none");
        $("#TC input").val(''); //清空弹窗内数据
        $("#TC input").attr("disabled", "disabled"); //添加不可编辑的属性
        $("#TC select option").attr("disabled", ""); //添加不可编辑的属性
        $("#TC i").css("display", "none"); //添加不可编辑的属性
    }
    //还原创建
    function recScreeningCondition() {
        // $("label:contains('属于类型：')").parent().insertAfter($("label:contains('品牌：')").parent())
    }

    //删除数据方法 操作对象 data 下标 数组对象
    function delObjData(obj, data, ind) {
        var arr = []
        layui.each(data, (i, d) => {
            arr.push(parseInt(d.tableId))
        })
        console.log('删除的数据', arr)
        layer.confirm('真的删除行么', function (index) {
            AJAX(oveUrl + "/layuiTabCols/deleTab", JSON.stringify(arr), 'DELETE', null, null, function (res) {
                console.log(res)
                if (res.code == 200) {
                    if (obj != null) {
                        obj.del();
                    } else {
                        var tabData = table.cache[tabElemId];
                        console.log(tabData);
                        layui.each(tabData, function (i, d) {
                            layui.each(arr, function (j, v) {
                                if (parseInt(d['tableId']) == parseInt(v)) {
                                    tabData.splice(i, 1);
                                }
                            });
                        });
                        console.log(tabData);
                        table.reload(tabElemId, {
                            data: tabData
                        });
                    }
                    layer.close(index);
                }
                window.parent.left.isOPO = true;
            });
        });
    }


    $_$("body").on("click", function (event) {
        $_$("div[dtree-id][dtree-select]").removeClass("layui-form-selected");
        $_$("div[dtree-id][dtree-card]").removeClass("dtree-select-show layui-anim layui-anim-upbit");
    });


});



//页面加载完成后执行事件
window.onload = function () {
    window.parent.setProgressFun(null, 10)
    //定时器 查找是否找到按钮后结束加载弹框
    // var sit = setInterval(function () {
    //     //关闭父类加载弹框
    //     globalParentLoadingFunClose(null);
    //     this.clearInterval(sit); //清除定时器
    // }, 2000);
}

//获取左边点击的编号
function getid(obj) {
    console.log(obj);
    switch (atObjHtml.treeLeft) {
        case 'layuiTabCols/seleTree':
            tree.atObj.htmlTreeName = obj.context;
            var v = obj.context.split('-')[1]
            console.log(v)
            if (v != undefined) {
                table.reload(tabElemId, {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    },
                    where: {
                        elem: v,
                    }
                });
            } else {
                alert('名称格式错误');
            }
            break;

        default:
            break;
    }


}